package auto

import (
	"fmt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	logger "github.com/sirupsen/logrus"
	"os"
	"path"
	"strings"
	"time"
)

func init() {
	InitLog("request", 1024*1024*200, time.Hour*24*7)
}

type FileFormatter struct {
}

func (l FileFormatter) Format(entry *logger.Entry) ([]byte, error) {
	//funks := strings.SplitN(entry.Caller.Function, ".", 2)
	msg := fmt.Sprintf("[%s] [%s] %s\n",
		entry.Time.Format("2006-01-02 15:04:05,000"),
		strings.ToUpper(entry.Level.String()),
		//path.Join(funks[0], "/", filepath.Base(entry.Caller.File)),
		//entry.Caller.Line,
		entry.Message)
	return []byte(msg), nil
}
func InitLog(logName string, maxSize int64, maxAge time.Duration) {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(" 获取当前路径失败")
		os.Exit(1)
	}
	filePaths := path.Join(pwd, "logs", logName)
	writer, _ := rotatelogs.New(
		filePaths+".%Y%m%d%H%M",            //分割后文件名
		rotatelogs.WithLinkName(filePaths), //软连接指向最新文件
		rotatelogs.WithMaxAge(maxAge),      // 最大保留时间(time.Hour*24*7) 一个星期
		//rotatelogs.WithRotationTime(rotaTime),     // 设置滚动时间
		rotatelogs.WithRotationSize(maxSize), //设置日志文件最大存储大小为10MB (1024*1024*10)
	)
	writeMap := lfshook.WriterMap{
		logger.TraceLevel: writer,
		logger.DebugLevel: writer,
		logger.InfoLevel:  writer,
		logger.WarnLevel:  writer,
		logger.ErrorLevel: writer,
		logger.FatalLevel: writer,
		logger.PanicLevel: writer,
	}
	logger.AddHook(lfshook.NewHook(writeMap, new(FileFormatter)))
	logger.SetOutput(os.Stdout)
	logger.SetReportCaller(true)
	logger.SetFormatter(&FileFormatter{})
}
